package com.fancon.android.gardenjokesx.activity;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.io.StringWriter;
import java.io.UnsupportedEncodingException;
import java.io.Writer;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TextView;

import com.fancon.android.gardenjokesx.GardenJokesBaseActivity;
import com.fancon.android.gardenjokesx.R;
import com.fancon.android.gardenjokesx.entity.Country;
import com.fancon.android.gardenjokesx.entity.FacebookUser;
import com.fancon.android.gardenjokesx.entity.User;
import com.fancon.android.gardenjokesx.rpc.GardenJokesApiConnect;
import com.fancon.android.gardenjokesx.rpc.JsonPaser;
import com.fancon.android.gardenjokesx.social.DatabaseHelper;
import com.fancon.android.gardenjokesx.social.SocialUntil;
import com.fancon.android.gardenjokesx.utils.Constant;
import com.fancon.android.gardenjokesx.utils.Spinners;
import com.fancon.android.gardenjokesx.utils.UserUtil;
import com.fancon.android.multithread.RequestUI;
import com.fancon.android.ui.widget.FanconProgressBar;

public class EditYouElementActivity extends GardenJokesBaseActivity implements OnClickListener{
	private View backBtn;
	private User userProfile;
	private Button btnSave;
	
	// U03 views
	private Spinner mSpnYear = null;
	private Spinner mSpnMonth = null;
	private Spinner mSpnDay = null;

	private Button mBtnShowBirthDate;
	private Button mBtnShowGender;
	private Button mBtnFacebookCopy;
	private Spinner mSpnGender;
	private Spinner mSpnInterest;
	private Spinner mSpnBloodType;
	private Spinner mSpnCountry;
	private EditText mEditCity;
	public Boolean isFirstTime = true;
	private Spinners mSpinners;
	private String publicBirhdate;
	private String publicGender;
	List<Country> lstCountry = new ArrayList<Country>();
	public DatabaseHelper db = new DatabaseHelper(EditYouElementActivity.this);
	public static Boolean fromFacebook = false;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.mesx_edit_element_u03);
		
		TextView title = (TextView) findViewById(R.id.action_bar_textview_title);
		title.setText(getText(R.string.edit_you_element));
		
		mSpnYear = (Spinner) findViewById(R.id.u03_spnYear);
		mSpnMonth = (Spinner) findViewById(R.id.u03_spnMonth);
		mSpnDay = (Spinner) findViewById(R.id.u03_spnDay);
		publicBirhdate = "0";
		publicGender = "0";
		mBtnShowBirthDate = (Button) findViewById(R.id.u03_btnShowBirthDate);
		mBtnShowBirthDate.setOnClickListener(this);
		mBtnShowGender = (Button) findViewById(R.id.u03_btnShowGender);
		mBtnShowGender.setOnClickListener(this);
		mSpnGender = (Spinner) findViewById(R.id.u03_spnGender);
		mSpnInterest = (Spinner) findViewById(R.id.u03_spnInterest);
		mSpnBloodType = (Spinner) findViewById(R.id.u03_spnBloodType);
		mSpnCountry = (Spinner) findViewById(R.id.u03_spnCountry);
		mEditCity = (EditText) findViewById(R.id.u03_editCity);
		mBtnFacebookCopy = (Button) findViewById(R.id.u03_btnFacebookCopy);
		mBtnFacebookCopy.setOnClickListener(this);
		btnSave = (Button) findViewById(R.id.save);
		btnSave.setOnClickListener(this);
		backBtn = findViewById(R.id.action_bar_button_back);
		backBtn.setOnClickListener(this);
		String jsonContries = readJsonContries();
		Log.d("countries", jsonContries);
		
		mSpinners = new Spinners(EditYouElementActivity.this);
		mSpinners.createListGender(mSpnGender, "0");
		mSpinners.createListInterest(mSpnInterest, "M");
		mSpinners.createBirthDatePic(mSpnYear, mSpnMonth, mSpnDay, null);
		mSpinners.createListBloodType(mSpnBloodType, "A");
		mSpinners
		.setButtonState(mBtnShowBirthDate, publicBirhdate);
		mSpinners.setButtonState(mBtnShowGender, publicGender);
		UserRequest youElement = new UserRequest("editElement", EditYouElementActivity.this);
		getGlobalState().getRequestQueue().addRequest(youElement);
		
	}
	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		if(v == backBtn){
			finish();
		}
		if (v == mBtnShowBirthDate) {
			// Change public birth date
			if (publicBirhdate != "") {
				Log.d("show date", "ok");
				if (publicBirhdate.equals(Constant.PUBLIC)) {
					mSpinners
							.setButtonState(mBtnShowBirthDate, Constant.NOT_PUBLIC);
					publicBirhdate = Constant.NOT_PUBLIC;
				} else {
					mSpinners.setButtonState(mBtnShowBirthDate, Constant.PUBLIC);
					publicBirhdate = Constant.PUBLIC;
				}
			}
		} else if (v == mBtnShowGender) {
			// Change public birth date
			if (publicGender != "") {
				Log.d("show gender", "ok");
				if (publicGender.equals(Constant.PUBLIC)) {
					mSpinners.setButtonState(mBtnShowGender, Constant.NOT_PUBLIC);
					publicGender = Constant.NOT_PUBLIC;
				} else {
					mSpinners.setButtonState(mBtnShowGender, Constant.PUBLIC);
					publicGender = Constant.PUBLIC;
				}
			}

		} else if (v == btnSave) {
			// Update user information
			String country = mSpnCountry.getSelectedItem().toString();
			if (country != getResources().getString(R.string.S02_required)) {
				UpdateUserRequest request = new UpdateUserRequest("edit", EditYouElementActivity.this);
				getGlobalState().getRequestQueue().addRequest(request);
			} else {
				showErrorDialog("Country name is required");
			}
		} else if (v == mBtnFacebookCopy) {
			copyFacebook(UserUtil.getInfoUserLogin(EditYouElementActivity.this).getUser_id());
		}
	}
	
	  @Override
		public void onResume() {
			// TODO Auto-generated method stub
			super.onResume();
//			TabHostActivity.showTabs();
			Log.d("resume", "resume");
			if (fromFacebook) {
				Log.d("resume", "face");
				if (db.isFacebookLinked(UserUtil.getInfoUserLogin(EditYouElementActivity.this).getUser_id())) {
					Log.d("resume", "linked");
					FacebookUser fbUser = db.getFacebookUser(UserUtil.getInfoUserLogin(EditYouElementActivity.this).getUser_id());
					 String accessToken = fbUser.getAccessToken();
					 Log.d("token", accessToken);
					 User user = new User();
					 SocialUntil sc = new SocialUntil(EditYouElementActivity.this);
					 user = sc.userInfoFB(accessToken);
					 displayUserElement(user, true);
					 fromFacebook = false;
				}
			}
		
			
		}
	
	public String readJsonContries() {
		InputStream is = getResources().openRawResource(R.raw.countries);
		Writer writer = new StringWriter();
		char[] buffer = new char[1024];
		try {
		    Reader reader = null;
			try {
				reader = new BufferedReader(new InputStreamReader(is, "UTF-8"));
			} catch (UnsupportedEncodingException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		    int n;
		    try {
				while ((n = reader.read(buffer)) != -1) {
				    writer.write(buffer, 0, n);
				}
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		} finally {
		    try {
				is.close();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}

		String jsonString = writer.toString();
		Log.d("string", jsonString);
		return jsonString;
	}
	
	/**
	 * Request user element
	 * 
	 * @author DuyTX
	 *
	 */
	class UserRequest extends RequestUI {
		private Activity context;
		private Boolean isFirst = true;
		private FanconProgressBar progress;

		public UserRequest(Object key, Activity activity) {
			super(key, activity);
			context = activity;
			if (isFirst) {
				progress = FanconProgressBar.show(context, context.getString(R.string.common_loading));
			}

		}

		@Override
		public void execute() {
			// TODO Auto-generated method stub
			
			List<NameValuePair> youDataValuePairs = new ArrayList<NameValuePair>(
					1);
			youDataValuePairs.add(new BasicNameValuePair("user_id", UserUtil.getInfoUserLogin(context).getUser_id()));
			GardenJokesApiConnect api = new GardenJokesApiConnect(context);
			String youProfile = "";
			youProfile = api.execGet(context, GardenJokesApiConnect.GROUP_U,
					"getYOUData", youDataValuePairs);

			JsonPaser jP = new JsonPaser();
			userProfile = new User();
			userProfile = null;
			Log.v("youData", youProfile);
			if (youProfile.length() > 0) {
				userProfile = jP.getUser(youProfile);
			} else {
				btnSave.setClickable(false);
			}
			Log.v("StringResult", youProfile);
		}

		@Override
		public void executeUI(Exception ex) {
			// TODO Auto-generated method stub

			if (userProfile != null) {

				displayUserElement(userProfile, false);
			}

			if (progress != null) {
				progress.dismiss();
			}
			isFirst = false;

		}

	}
	
	
	/**
	 * Display user element
	 * 
	 * @param user
	 */
	private void displayUserElement(User user, Boolean fromFacebook) {
		if (user != null) {
			Log.d("vao display", "OK");
			// Show birth date
			String birthDay = user.getBirthday();
			if (user.getBirthday() != null) {
				mSpinners
					.createBirthDatePic(mSpnYear, mSpnMonth, mSpnDay, birthDay);
				Log.d("bot day", "bot day");
			}
			if (user.getPublic_birthday() != null) {
				publicBirhdate = user.getPublic_birthday();
				mSpinners.setButtonState(mBtnShowBirthDate, publicBirhdate);
			}

			// Show gender
			if ( user.getMale() != null) {
				String male = user.getMale();
				mSpinners.createListGender(mSpnGender, male);
				// OnChange Spinner gender and interested
				mSpnGender.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
				    public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) { 
				        // Your code here
				    	switch (i) {
						case 0:
							if (!isFirstTime) {
							mSpinners.createListInterest(mSpnInterest, "M");
							} else {
								isFirstTime = false;
							}
							break;
						case 1:
							if (!isFirstTime) {
							mSpinners.createListInterest(mSpnInterest, "F");
							} else {
								isFirstTime = false;
							}
							break;
							
						default:
							break;
						}
				    } 

				    public void onNothingSelected(AdapterView<?> adapterView) {
				        return;
				    } 
				}); 
			}
			
			if (user.getPublic_gender() != null) {
				publicGender = user.getPublic_gender();
				mSpinners.setButtonState(mBtnShowGender, publicGender);
			}
			
			if (user.getInterested() != null) {
				String interested = user.getInterested();
				mSpinners.createListInterest(mSpnInterest, interested);
			}

			// Blood type
			if (user.getBlood_type() != null) {
				String bloodType = user.getBlood_type();
				mSpinners.createListBloodType(mSpnBloodType, bloodType);
			}
			JsonPaser jP = new JsonPaser();
			String jsonContries = readJsonContries();
			lstCountry = jP.getListCountry(jsonContries);
			mSpinners.createListCountry(mSpnCountry, null ,lstCountry);	
			// Location
			if (user.getCurrent_country() != null) {
				String country = user.getCurrent_country();
				mSpinners.createListCountry(mSpnCountry, country ,lstCountry);
			}
			
			String city = user.getCurrent_city();
			if (city != null) {
				if (user.getCurrent_country() != null) {
					try {
						city = URLDecoder.decode(city, "UTF-8");
					} catch (UnsupportedEncodingException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
					if (fromFacebook) {
						int index  = city.lastIndexOf(",");
						if (index != -1) {
						city = city.substring(0, index);
					}
					}
				}
				
				mEditCity.setText(city);
			}
			
			
			
		}
	}
	
	/**
	 * Request user element
	 * 
	 * @author DuyTX
	 *
	 */
	class UpdateUserRequest extends RequestUI {
		private Activity context;
		private Boolean isFirst = true;
		private FanconProgressBar progress;
		Boolean success = false;

		public UpdateUserRequest(Object key, Activity activity) {
			super(key, activity);
			context = activity;
			if (isFirst) {
				progress = FanconProgressBar.show(context, context.getString(R.string.common_loading));
			}

		}

		@Override
		public void execute() {
			// TODO Auto-generated method stub
			Log.d("update you data", "ok");
			success = updateYouData();
		}

		@Override
		public void executeUI(Exception ex) {
			// TODO Auto-generated method stub
			
			if (progress != null) {
				progress.dismiss();
			}
			isFirst = false;
			if (success) {
				finish();
			} else {
//				showErrorDialog("Can not save information");
			}

		}

	}
	/**
	 * show error dialog when have error
	 * 
	 * @param msg
	 */
	public void showErrorDialog(String msg) {

		AlertDialog.Builder builder = new AlertDialog.Builder(EditYouElementActivity.this);
		builder.setMessage(msg).setCancelable(true)
				.setNegativeButton("OK", new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int id) {
						dialog.cancel();
					}
				});
		AlertDialog alert = builder.create();
		alert.show();
	}
	
	/**
	 * Update you data
	 * 
	 * @param nameValuePairs
	 * @return
	 */
	private Boolean updateYouData() {
		String city = mEditCity.getText().toString();
		String male = mSpnGender.getSelectedItem().toString();
		Log.d("vao update", "ok");
		String interested = getInterest(mSpnInterest.getSelectedItem()
				.toString());
		String bloodType = mSpnBloodType.getSelectedItem().toString();
		if (bloodType.equals(getString(R.string.S02_not_public))) {
			bloodType = "S";
		}
		if (bloodType.equals("AB")) {
			bloodType = "X";
		}
		String country = mSpnCountry.getSelectedItem().toString();
		String birthday = mSpinners.getBirMonth() + "/"
				+ mSpinners.getBirDay() + "/" + mSpinners.getBirYear();
		List<NameValuePair> youDataValuePairs = new ArrayList<NameValuePair>(
				11);
		youDataValuePairs.add(new BasicNameValuePair("user_id", UserUtil.getInfoUserLogin(EditYouElementActivity.this).getUser_id()));
		youDataValuePairs.add(new BasicNameValuePair("male",
				getGender(male)));
		Log.d("gender", mSpnGender.getSelectedItem().toString());
		Log.d("gender1", getGender(male));
		youDataValuePairs.add(new BasicNameValuePair("interested",
				interested));
		try {
			youDataValuePairs.add(new BasicNameValuePair("current_city", URLEncoder.encode(city, "UTF-8").replace("+", "%20")));
		} catch (UnsupportedEncodingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		youDataValuePairs.add(new BasicNameValuePair("current_country",
				country));
		youDataValuePairs.add(new BasicNameValuePair("blood_type",
				bloodType));
		youDataValuePairs.add(new BasicNameValuePair("birthday", birthday));
		youDataValuePairs.add(new BasicNameValuePair("public_birthday",
				publicBirhdate));
		youDataValuePairs.add(new BasicNameValuePair("public_gender",
				publicGender));
		youDataValuePairs.add(new BasicNameValuePair("longitude",
			String.valueOf(UserUtil.getInfoUserLogin(EditYouElementActivity.this).getLongitude())));
		youDataValuePairs.add(new BasicNameValuePair("latitude",
				String.valueOf(UserUtil.getInfoUserLogin(EditYouElementActivity.this).getLatitude())));
		
		GardenJokesApiConnect api = new GardenJokesApiConnect(EditYouElementActivity.this);
		String result = api.execPost(getApplicationContext(),
				GardenJokesApiConnect.GROUP_S, "registerYOUData", youDataValuePairs);
		
		if (result == null || result.equals("")) {
			return false;
		}
			Boolean report;
			JSONObject jObject;
			report = false;
			Log.v("StringResultUpdate", result);
			try {
				jObject = new JSONObject(result);
				report = jObject.getBoolean("is_success");
			} catch (JSONException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}

		return report;
	}
	
	private String getInterest(String interest) {
		String str = "";
		if (interest.equals(getString(R.string.S02_male))) {
			str = "M";
		} else if (interest.equals(getString(R.string.S02_female))) {
			str = "F";
		} else
			str = "A";
		return str;
	}
	private String getGender(String gender) {
		String str = "0";
		if (gender.equals(getString(R.string.S02_male)))
			str = "1";
		else if (gender.equals(getString(R.string.S02_female)))
			str = "0";
		return str;
	}
	
	/**
	 * Copy information from facebook to meshtiles
	 */
	private void copyFacebook(String userId) {
		 

		if (db.isFacebookLinked(userId)) {
			AlertDialog.Builder builder = new AlertDialog.Builder(EditYouElementActivity.this);
			builder.setMessage(getResources().getString(R.string.S02_MSG_S0001))
					.setCancelable(false)
					.setNegativeButton(this.getResources().getString(R.string.common_calcel),
							new DialogInterface.OnClickListener() {
								public void onClick(DialogInterface dialog,
										int id) {
									dialog.cancel();
								}
							})
					.setPositiveButton(this.getResources().getString(R.string.common_ok),
							new DialogInterface.OnClickListener() {
								public void onClick(DialogInterface dialog,
										int id) {
									// TODO copy user information from facebook.
									 FacebookUser fbUser = db.getFacebookUser(UserUtil.getInfoUserLogin(EditYouElementActivity.this).getUser_id());
									 String accessToken = fbUser.getAccessToken();
									 Log.d("token", accessToken);
									 User user = new User();
									 SocialUntil sc = new SocialUntil(EditYouElementActivity.this);
									 user = sc.userInfoFB(accessToken);
									 displayUserElement(user, true);
									dialog.cancel();

								}
							});
			AlertDialog alert = builder.create();
			alert.show();
		} else {
			Intent i = new Intent(this, S03_2Activity.class);
			i.putExtra(Constant.SCREEN_ID, Constant.U03);
			startActivity(i);
		}
	}
}
